import java.util.HashMap;
import java.util.Map;

// 连续数组
//测试链接 https://leetcode.cn/problems/contiguous-array/description/
public class FindMaxLength {
    //解题思路：转化为和为0的最长子树组
    public int findMaxLength(int[] nums) {
        Map<Integer,Integer> map = new HashMap<>();
        map.put(0,-1);//默认存在前缀和为1的情况

        int len = 0, sum = 0;
        for(int i = 0; i < nums.length; i++){
            sum += nums[i] == 0 ? -1 : 1;

            if(map.containsKey(sum)){
                len = Math.max(i-map.get(sum),len);
            }else{
                map.put(sum, i);
            }

        }
        return len;
    }
}
